home *** CD-ROM | disk | FTP | other *** search
- Path: fido.asd.sgi.com!austern
- From: bill@gibbons.org (Bill Gibbons)
- Newsgroups: comp.std.c++
- Subject: Re: sample auto_ptr template
- Date: 08 Apr 1996 10:16:05 PDT
- Organization: -none-
- Approved: austern@isolde.mti.sgi.com
- Message-ID: <bill-0804960932250001@bgibbons.vip.best.com>
- References: <009A04DA6A831C40.49800EAC@ittpub.nl> <4k0m72$gm1@jabba.lehman.com> <bill-0504961003150001@bgibbons.vip.best.com> <4k4noe$igl@jabba.lehman.com>
- NNTP-Posting-Host: isolde.mti.sgi.com
- X-Original-Date: Mon, 08 Apr 1996 09:32:25 -0700
- X-Auth: PGPMoose V1.1 PGP comp.std.c++
- iQBVAwUBMWlJ1ky4NqrwXLNJAQEHjgH/czVIK5XtZNJ9zkSpRevuxQcJcFWdDfzo
- Ri4BbF6sB3H06GY9+bHY3lKMG05a9pW1s39DPT2Pzz7uyF8oMZ/pgw==
- =j2Xs
- Originator: austern@isolde.mti.sgi.com
-
- In article <4k4noe$igl@jabba.lehman.com>, ajay@lehman.com (Ajay Kamdar) wrote:
-
- > ...
- > It is not clear at all that the copy semantics of auto_ptr
- > are essential for exception-safe transfer of resources.
- > The same example coded as follows does not use
- > the copy semantics of auto_ptr:
- >
- >
- > extern X* get_X(); // returns a resource acquired
- > // by the callee, to be deleted
- > // by the caller.
- >
- > void f() {
- > auto_ptr<X> ptr = get_X();
- > // resource allocated by get_X()
- > ...
- > }
- >
- > And get_X() is not unnecessarily complicated either:
- >
- > X* get_X()
- > {
- > auto_ptr<X> p = new X;
- >
- > // ... stuff that could throw an exception
- >
- > // We got here. Means normal return.
- > return p.release();
- > }
- >
- > What's wrong with this? It doesn't require copy semantics
- > for auto_ptr. Yet both the caller and the callee
- > are exception safe and there is no loss of clarity.
-
- The problem is that it requires handling the raw pointer.
- Any time you transfer ownership by using release() to extract
- the raw pointer and then later use the raw pointer to
- construct another auto_ptr, there is a window where there is
- no exception safety.
-
- Of course you can carefully craft the code to make sure that
- no exceptions can be propagated during the window. But there
- are two problems:
-
- (1) The maintainers of the code may not be as careful about
- exception safety. When everything is handled by
- auto_ptr the risk of bugs creeping in is smaller. Such
- bugs are very difficult to find by testing.
-
- (2) The interface of get_X does not implicitly document
- that the returned pointer refers to an object which
- should be automatically deleted on an exception.
-
- --
- Bill Gibbons
- bill@gibbons.org
- ---
- [ comp.std.c++ is moderated. To submit articles: Try just posting with your
- newsreader. If that fails, use mailto:std-c++@ncar.ucar.edu
- comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
- Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
- Comments? mailto:std-c++-request@ncar.ucar.edu
- ]
-